package org.sxf.app.sign.activity;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.util.LogUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import org.sxf.app.sign.R;
import org.sxf.app.sign.activity.BaseActivity;
import org.sxf.app.sign.adapter.SchoolListAdapter;
import org.sxf.app.sign.biz.BaseBiz;
import org.sxf.app.sign.biz.LoginBiz;
import org.sxf.app.sign.biz.SystemInitBiz;
import org.sxf.app.sign.constants.Constants;
import org.sxf.app.sign.data.DataCacheSingleton;
import org.sxf.app.sign.provider.Client;
import org.sxf.app.sign.provider.MsgHandler;
import org.sxf.app.sign.utils.ConfigFileUtilsSingleton;
import org.sxf.app.sign.utils.Utility;
import org.sxf.app.sign.widgt.T;

import Ice.ConnectionRefusedException;
import Ice.SocketException;
import Ice.TimeoutException;
import Ice.UnknownException;

public class SplashActivity extends BaseActivity implements BaseBiz.OnBizCallBackListener {

    private SystemInitBiz mInitSystemBiz;
    private LoginBiz mLoginBiz;

    private SchoolListAdapter mSchoolListAdapter;


    @ViewInject(R.id.login_layout)
    private RelativeLayout mLoginLayout;
    @ViewInject(R.id.edit_text_user)
    private EditText mEditTextViewUser;
    @ViewInject(R.id.edit_text_pw)
    private EditText mEditTextViewPw;
    @ViewInject(R.id.wrong_pw)
    private TextView mPwWrongTextView;


    @ViewInject(R.id.select_layout)
    private RelativeLayout mSelectLayout;
    @ViewInject(R.id.textView2)
    private TextView mListHintTextView;
    @ViewInject(R.id.listView)
    private ListView mSchoolListView;
    @ViewInject(R.id.confirm_bt)
    private TextView mConfirmBt;


    private String mTipDetail = "";



    @OnClick(R.id.login_bt)
    public void onClickLoginView(View view){

        if ("".equals(mEditTextViewUser.getText().toString())){
            T.s(this, getString(R.string.login_user_empty));
            return;
        }

        if ("".equals(mEditTextViewPw.getText().toString())){
            T.s(this, getString(R.string.login_pw_empty));
            return;
        }

        popLoadingDialog(getString(R.string.login_doing_login));
        DataCacheSingleton.getInstance().setStudentNo(mEditTextViewUser.getText().toString());
//        DataCacheSingleton.getInstance().setPwMd5(MD5Utils.MD5(mEditTextViewPw.getText().toString()));
        DataCacheSingleton.getInstance().setPwMd5(mEditTextViewPw.getText().toString());
        mLoginBiz.login();
        mPwWrongTextView.setVisibility(View.INVISIBLE);
    }

    @OnClick(R.id.textView2)
    public void onClickHintTextView(View view){
        popLoadingDialog(getString(R.string.select_loading));
        mListHintTextView.setVisibility(View.GONE);
        mLoginBiz.queryCorpList();
    }

    @OnClick(R.id.confirm_bt)
    public void onClickConfirmBt(View view){

//        popLoadingDialog(getString(R.string.select_loading));


        ConfigFileUtilsSingleton.getInstance().writeConfig(Constants.CONFIG_KEY_SCHOOL_CODE, DataCacheSingleton.getInstance().getSchoolBeanList().get(mSchoolListAdapter._selectPosition).corp_id);

//        mInitSystemBiz.startInit();

        DataCacheSingleton.getInstance().setSchoolCode(DataCacheSingleton.getInstance().getSchoolBeanList().get(mSchoolListAdapter._selectPosition).corp_id);
        gotoLoginView();

    }

    @OnClick(R.id.re_select_xq)
    public void onClickReSelectXq(View view){
        popLoadingDialog(getString(R.string.select_loading));
        gotoSelectSchoolView();
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);

        ViewUtils.inject(this);




        DataCacheSingleton.getInstance().setIceServerConfig("sign:tcp -t 6000 -h 192.168.8.105 -p 18009");


        setTheme(android.R.style.Theme_Holo_NoActionBar);


        initUI();
        initBiz();


        if (isStartFromLogout()){
            if (!"".equals(mTipDetail)){
                showAlertDialog(getString(R.string.tip), mTipDetail);
            }
        }


//        LogUtils.d("dec:" +MsgHandler.msgDecrypt("920953563BDDCFC0F1AFAA210DE3CFB0A062E5C6014EED8E61BBA0B7872B641C90000441793DE68400BA183EAA726FAF270746E127BE0254A24A5B1E2A5C259C67BFCFA505AC43C171546FA5B93FCFF6DC3FC367C78297D6"));

    }

    public boolean isStartFromLogout(){

        Intent intent = getIntent();
        if (intent == null) {
            return false;
        }
        String flagStr;
        flagStr = intent.getStringExtra("s_logout");
        if (flagStr == null){
            return false;
        }

        mTipDetail = flagStr;

        return true;
    }


    private void initUI(){
        mSchoolListAdapter = new SchoolListAdapter(this.getLayoutInflater());
        mSchoolListView.setAdapter(mSchoolListAdapter);
        mSchoolListView.setOnItemClickListener(mSchcoolListSelectedItemClickListener);
    }

    private void initBiz(){
        ConfigFileUtilsSingleton.getInstance().createSP(getApplicationContext());
        mInitSystemBiz = new SystemInitBiz(this, this);
        mLoginBiz = new LoginBiz(this, this);
        mInitSystemBiz.startInit();

    }



    private void gotoLogin(){
        mLoginBiz.checkLoginInfo();
    }

    private void gotoLoginView(){
        mLoginLayout.setVisibility(View.VISIBLE);
        mSelectLayout.setVisibility(View.GONE);
        mEditTextViewUser.setText(DataCacheSingleton.getInstance().getStudentNo());
        mEditTextViewPw.setText(DataCacheSingleton.getInstance().getPwMd5());
    }

    private void gotoSelectSchoolView(){
        mLoginLayout.setVisibility(View.GONE);
        mSelectLayout.setVisibility(View.VISIBLE);
        mListHintTextView.setVisibility(View.INVISIBLE);
        mConfirmBt.setEnabled(false);
        ConfigFileUtilsSingleton.getInstance().clearConfig(Constants.CONFIG_KEY_SCHOOL_CODE);
        DataCacheSingleton.getInstance().setSchoolCode("");
        mLoginBiz.queryCorpList();
    }

    private void gotoSelectCorpView(){
        mLoginLayout.setVisibility(View.GONE);
        mSelectLayout.setVisibility(View.VISIBLE);
        mListHintTextView.setVisibility(View.INVISIBLE);
    }

    private void gotoMainView(){
        startActivity(new Intent(this, MainTabActivity.class));
        overridePendingTransition(R.anim.act_fade_in, R.anim.act_null);
        finish();
    }

    private void refreshSchoolConfirmBt(){
        try {
            if (DataCacheSingleton.getInstance().getSchoolBeanList().size() != 0){
                mConfirmBt.setEnabled(true);
            }else {
                mConfirmBt.setEnabled(false);
            }
        }catch (Exception e){
            mConfirmBt.setEnabled(false);
        }

    }

    AdapterView.OnItemClickListener mSchcoolListSelectedItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            mSchoolListAdapter._selectPosition = position;
            mSchoolListAdapter.notifyDataSetChanged();
        }
    };


    @Override
    public void onBizResult(int biz, Object result) {
        switch (biz){
            case SystemInitBiz.BIZ_INIT_SUCCESS:
                mLoginBiz.checkLoginInfo();
                break;
            case LoginBiz.BIZ_GOTO_LOGIN_VIEW:
                gotoLoginView();
                break;
            case LoginBiz.BIZ_CHECK_LOGIN_INFO_PASS:
                gotoMainView();
                break;
            case LoginBiz.BIZ_LOGIN_QUERY_CORP_SUCCESS:

                mSchoolListAdapter.notifyDataSetChanged();
                mListHintTextView.setVisibility(View.GONE);
                refreshSchoolConfirmBt();
                dismissLoadingDialog();
                break;
            case LoginBiz.BIZ_GOTO_SELECT_CORP_VIEW:
                popLoadingDialog(getString(R.string.select_loading));
                gotoSelectCorpView();
                break;
            case LoginBiz.BIZ_LOGIN_PW_WRONG:
                dismissLoadingDialog();
                mPwWrongTextView.setVisibility(View.VISIBLE);
                break;
            case LoginBiz.BIZ_LOGIN_FAIL:
                dismissLoadingDialog();
                mPwWrongTextView.setVisibility(View.VISIBLE);
                break;
            case LoginBiz.BIZ_LOGIN_SUCCESS:
                dismissLoadingDialog();
                gotoMainView();
                break;
        }
    }

    @Override
    public void onBizError(int biz, Object result) {
        switch (biz){
            case SystemInitBiz.ERROR_NET_FAIL:
                dismissLoadingDialog();
                T.s(this, getString(R.string.net_error));
                break;
            case LoginBiz.ERROR_SIGNATURE_FAIL:
                dismissLoadingDialog();
                T.s(this, getString(R.string.net_error));
                break;
            case LoginBiz.ERROR_UNKNOWN_FAIL:
                dismissLoadingDialog();
                T.s(this, getString(R.string.net_error));
                break;
            case LoginBiz.ERROR_TOKEN_EXPIRED:
                showAlertDialog(getString(R.string.tip), getString(R.string.login_expired));
                dismissLoadingDialog();
                gotoLoginView();
                break;
            case LoginBiz.ERROR_QUERY_CORP_FAIL:
                mSchoolListAdapter.notifyDataSetChanged();
                mListHintTextView.setVisibility(View.VISIBLE);
                refreshSchoolConfirmBt();
                dismissLoadingDialog();
                break;
            case LoginBiz.ERROR_LOGIN_NET_ERROR:
                dismissLoadingDialog();
                T.s(this, getString(R.string.net_error));
                break;
        }
    }
}
